import * as ioredis from 'ioredis'
import * as _ from 'lodash'
import { IRedisConfig } from '../../interface/IFace';
import * as Q from 'q'
export class RedisCache{
    private _sub:any={};
    private _channels:any=[];
    private _redis;
    private _config:IRedisConfig;
    constructor(config:IRedisConfig){
        this._config = config;
        this._redis = new ioredis(this._config)
    };
    public set(key:string,value:any,expire?:number){
        if(_.isNumber(expire)){
            this._redis.set(key,value,'EX',expire)
        }else{
            this._redis.set(key,value)
        }
    }
    public async get(key:string):Promise<any>{
        return this._redis.get(key)
    }
    public async getSync(key:string){
        return await this._redis.get(key)
    }
    /**
     * 发布
     * @param channel
     * @param message
     */
    public publish(channel,message) {
        this._redis.publish(channel,"string" == typeof message?message:JSON.stringify(message))
    };
    /**
     * 订阅
     * @param channel
     * @param {Function} cb
     */
    public subscribe(channel) {
        if(!this._sub[channel]){
            let redis = require('ioredis');
            this._sub[channel] = new redis(this._config)
        }
        this._sub[channel].subscribe(channel,function (err,count) {

        });
        this._sub[channel].on('message',(pattern,channel,message)=> {
            try{
                var that = this;
                let json = JSON.parse(message);
                if(json.i&&json.i.length>2){
                    let C,A,i=json.i.split('/')
                    if(i.length==2) {
                        C = i[0];
                        A = i[1];
                        if("string"===typeof json.d && json.d.length>0){
                            json.d = JSON.parse(json.d);
                        }
                        let req={
                            body:json.d,
                            query:{
                                A:A,C:C,
                            },
                            params:{
                                A:A,C:C,
                            },
                            session:{
                                destroy:function(){}
                            }
                        },rep={
                            send:function (data,status=200) {
                                that._redis.publish("r_"+channel,{
                                    i:json.i,
                                    t:json.t,
                                    d:JSON.stringify(data),
                                    c:status
                                })
                            }
                        }
                    }
                }
            }catch (e){

            }
        });
    };
    /**
     * redis从获取请求数据
     * @param channel
     */
    public command=function (channel) {
        this.subscribe(channel,function (err,count) {
            
        })
    }
}